package main

import (
	"context"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"myuser/gorm-gen/model"
	"myuser/gorm-gen/query"
)

func main() {
	// 连接数据库
	db, err := gorm.Open(mysql.Open("gorm:gorm@tcp(192.168.1.18:3306)/gorm?charset=utf8&parseTime=True&loc=Local"))
	if err != nil {
		panic(fmt.Errorf("cannot establish db connection: %w", err))
	}
	query.SetDefault(db)
	// 增加数据
	u := query.User
	ctx := context.Background()
	users := []*model.User{{Username: "test1", Avatar: "test1"}, {Username: "test2", Avatar: "test2"}}
	u.WithContext(ctx).Create(users...)
	// 查询数据 https://gorm.io/gen/query.html
	seach1, _ := u.WithContext(ctx).Where(u.ID.Eq(1)).First()
	log.Println("通过id查询", seach1)
	// 更新数据 https://blog.csdn.net/Jeffid/article/details/126898000
	u.WithContext(ctx).Where(u.Username.Eq("test2")).Update(u.Username, "wpc")
	seach2, _ := u.WithContext(ctx).Where(u.Username.Eq("wpc")).First()
	log.Println("更新后的查询", seach2)
}
